var http = require('http');
var url = require('url');
var fs = require('fs');

function returnTextFile(response, filename) {
    fs.readFile(filename, function (err, data) {
        if (err) throw err;
        response.writeHead(200, 
                           {"Content-Length": data.length,
                            "Content-Type": "text/html"}
                          );
        response.write(data.toString());
        response.end();
    });
}

function returnBinaryFile(response, filename) {
    fs.readFile(filename, function (err, data) {
        if (err) throw err;
        response.writeHead(200, 
                           {"Content-Length": data.length}
                          );
        response.write(data);
        response.end();
    });
}

function onRequest(request, response) {

    console.log("Request ("+ request.url +") received.");

    var pathname = url.parse(request.url).pathname;
    switch (pathname) {
    case '/':
    case '/weather':
        returnTextFile(response, './weather.html');
        break;
    case '/js/display.js':
        returnTextFile(response, './display.js');
        break;
    case '/js/decode.js':
        returnTextFile(response, './decode.js');
        break;
    case '/js/jdataview.js':
        returnTextFile(response, './jdataview.js');
        break;
    case '/js/jquery.js':
        returnTextFile(response, './jquery.js');
        break;
    case '/data/tempc':
        returnBinaryFile(response, './tempc.cz');
        break;
    case '/data/humidity':
        returnBinaryFile(response, './humidity.cz');
        break;
    case '/data/pressure':
        returnBinaryFile(response, './pressure.cz');
        break;
    default:
        console.log("No request handler found for " + pathname);
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("404 Not Found\n");
        response.end();
    }
    return;
}


http.createServer(onRequest).listen(8888);

console.log('Server running at http://127.0.0.1:8888/');